<?php

namespace backend\controllers;

use bc\controller\BackendController;
use bc\model\wc\BookingModel;
use bc\util\backend\Page;
use bc\model\wc\BpointModel;
use bc\model\wc\DoctorModel;
use bc\model\wc\HospitalModel;
use bc\model\UserModel;
use bc\util\Uploader;

class BookingController extends BackendController
{
	
	protected $arrStatus = [1 => '未支付', 2 => '已支付', 3 => '送检中', 4 => '已出报告', 99 => '异常'];
	
	
	public function actionIndex()
	{
		$model = new BookingModel ();
		
		$bpointModel = new BpointModel();
		$doctorModel = new DoctorModel();
		$userModel = new UserModel();
		$hospitalModel = new HospitalModel();
		
		$hospitalList = $hospitalModel->getList('1 = 1');
		
		$doctorList = $doctorModel->getList('1 = 1');
		
		$params['bc_wc_booking.is_invalid'] = 1;
		
		$page = $this->get ( 'page', 1 );
		
		$model->columns = ['bc_wc_booking.*', 'bc_user.mobile', 'bc_user.real_name', 'bc_user.nick_name'];
		$model->sort = 'bc_wc_booking.id DESC';
		$list = $model->getList ( $params, $page, self::PAGE_SIZE );
		
		
		foreach ($list as &$item)
		{
			$bpoint = $bpointModel->getRowById($item['bpoint_id']);
			$item['bpoint_name'] = $bpoint['name'];
			
			$doctor = $doctorModel->getRowById($item['doctor_id']);
			$user = $userModel->getRowById($doctor['user_id']);
			$item['doctor_name'] = $user['real_name'];
			
			$hospital = $hospitalModel->getRowById($doctor['hospital_id']);
			$item['hospital_name'] = $hospital['name'];
			
		}
		
		$total = $model->getTotal ( $params );
		
		$pagination = new Page ( $total, self::PAGE_SIZE );
		
		$view ['list']         = $list;
		$view ['pagination']   = $pagination;
		$view ['hospital_ist'] = $hospitalList;
		$view ['doctor_list']  = $doctorList;
		$view ['arr_status']   = $this->arrStatus;
		return $this->render ( 'index', $view );
	}
	
	
	/**
	 * 
	 */
	public function actionEdit()
	{
		$id = $this->get ( 'id' );
		if (! $id)
			$this->redirect ( '/' );
		
		$doctorModel = new DoctorModel();
		$userModel = new UserModel();
		$hospitalModel = new HospitalModel();
		$bpointModel = new BpointModel();
			
		$model = new BookingModel ();
		$model->columns = ['bc_wc_booking.*', 'bc_user.mobile', 'bc_user.real_name', 'bc_user.nick_name', 'bc_user.idcard', 'bc_user.idcard_type'];
		$row = $model->getRowById ( $id );
		
		if (! $row)
			$this->redirect ( '/' );
		
			
		$bpoint = $bpointModel->getRowById($row['bpoint_id']);
		$row['bpoint_name'] = $bpoint['name'];
			
		
		$doctor = $doctorModel->getRowById($row['doctor_id']);
		$user = $userModel->getRowById($doctor['user_id']);
		$row['doctor_name'] = $user['real_name'];
			
		$hospital = $hospitalModel->getRowById($doctor['hospital_id']);
		$row['hospital_name'] = $hospital['name'];
			
		$view ['row'] = $row;
		$view ['arr_status']   = $this->arrStatus;
		
		return $this->render ( 'edit', $view );
	}
	
	/**
	 * 
	 */
	public function actionReport()
	{
		$id = $this->get('id');
		$this->nolayout();
		$view['id'] = $id;
		return $this->render('report', $view);
	}
	
	
	/**
	 * 批量上传预约单
	 */
	public function actionBatch()
	{
		$this->nolayout();
		return $this->render('batch');
	}
	
	public function actionBatchupload()
	{
		$msg = '未知请求！';
		//附件上传
		if($_FILES['report']['error'] == 0)
		{
			$inputFileName = $_FILES['report']['tmp_name'];
			$objPHPExcel = \PHPExcel_IOFactory::load($inputFileName);
			$sheetData = $objPHPExcel->setActiveSheetIndex(0)->toArray();
			foreach ($sheetData as $key=>$excel)
			{
				if($key > 0)
				{
					if( empty($excel[0]))
						break;
					$sample_no = $excel[3];//送检编号
					$blood_date = $excel[4];//抽血日期
					$outpatient_no = $excel[6];//门诊号
					$age = $excel[7];//年龄
					$pregnancy = $excel[8];//登记孕周
					$idcard = $excel[9];//身份证号
					$mobile = $excel[10];//手机号
					
					$bookingModel = new BookingModel();
					$bookingModel->columns = ['bc_wc_booking.id', 'bc_wc_booking.status'];
					$booking = $bookingModel->getList(['bc_user.mobile' => $mobile, 'bc_user.idcard' => $idcard]);
					
					
					if(empty($booking[0]))//插入线下数据
					{
						$userModel = new UserModel();
						
						$user = $userModel->getRow(['mobile' => $mobile]);
						if(!$user)
						{
							//创建用户
							$user_data['mobile'] = $mobile;
							$user_data['idcard'] = $idcard;
							$user_data['idcard_type'] = 1;
							$user_data['create_time'] = time();
							$user_data['update_time'] = time();
							$user_data['is_invalid'] = 1;
							$user_auto_id = $userModel->add($user_data);
							
						}
						else 
						{
							$user_auto_id = $user['id'];
						}
						
						$data['user_id'] = $user_auto_id;
						$data['status'] = 3;
						$data['pregnancy'] = $pregnancy;
						$data['age'] = $age;
						$data['blood_date'] = $this->formatDate($blood_date);
						$data['sample_no'] = $sample_no;
						$data['outpatient_no'] = $outpatient_no?$outpatient_no:'';
						$data['create_time'] = time();
						$data['update_time'] = time();
						$data['bpoint_id'] = 0;
						$data['doctor_id'] = 0;
						$data['is_invalid'] = 1;
						$bookingModel->add($data);
					}
					else 
					{
						//更新表数据
						if($booking[0]['status'] == 2)
							$data['status'] = 3;
						$data['pregnancy'] = $pregnancy;
						$data['age'] = $age;
						$data['blood_date'] = $this->formatDate($blood_date);
						$data['sample_no'] = $sample_no;
						$data['outpatient_no'] = $outpatient_no?$outpatient_no:'';
						$bookingModel->modify($data, $booking[0]['id']);
					}
				}
			}
			
			$msg = '执行完成，关闭窗口！';
		}
		
		echo $this->jsCloseWindow($msg);
		
	}
	
	/**
	 * 
	 */
	public function actionUpload()
	{
		$msg = '未知请求！';	
		if($this->getRequest()->isPost)
		{
			$id = $this->post('id');
			$model = new BookingModel();
			$row = $model->getRowById($id);
			if(!$id ||!$row )
			{
				$msg = '参数错误！';
			}
			else 
			{
				//附件上传
				if($_FILES['report'])
				{
					$up = new Uploader( 'report' , $this->getUploadConfig() );
					$info = $up->getFileInfo();
					if($info['state'] === 'SUCCESS')
					{
						$data['report_url'] = str_replace(UPLOAD_PATH, '', $info['url']);
						$data['status'] = 4;
						$model->modify($data, $id);
						$msg = '关闭窗口！';
					}
				}
				
			}
		}
		
		echo $this->jsCloseWindow($msg);
	}
	
	
	private function jsCloseWindow($msg)
	{
		$js =  '<button type="button" onclick="window.close();">';
		$js .= $msg;
		$js .= '</button>';
		return $js;
	}
	
	/**
	 * @return array
	 */
	private function getUploadConfig()
	{
		//上传文件目录
		$path = UPLOAD_PATH . 'upload/report/';
		//上传配置
		$config = array(
				"savePath" => $path ,             //存储文件夹
				"maxSize" => 100000000 ,                   //允许的文件最大尺寸，单位KB
				"allowFiles" => array( ".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp", ".pdf" )  //允许的文件格式
		);
			
		//背景保存在临时目录中
		$config[ "savePath" ] = $path;
		return $config;
	}
	
	private function formatDate($data)
	{
		//11-01-16 => 2016-11-01
		$result = preg_replace('/(\d{2})-(\d{2})-(\d{2})/', '20$3-$1-$2', $data);
		return date('Y-m-d', strtotime($result));
		
	}
}

